package com.aiex.framework.security.filter;

import cn.hutool.core.util.StrUtil;
import com.aiex.framework.web.base.Result;
import com.aiex.framework.web.utils.JacksonUtils;
import com.aiex.framework.web.utils.ServletUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Serial;
import java.io.Serializable;

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {


    @Serial
    private static final long serialVersionUID = 1778847417897013148L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        int code = HttpStatus.UNAUTHORIZED.value();
        response.setStatus(code);
        String msg = StrUtil.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
        ServletUtils.renderString(response, JacksonUtils.toJSONString(Result.error(code, msg)));
    }
}
